package com.mulanweb.handler.wechat;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.StrKit;
import com.mulanweb.db.common.Constant;
import com.mulanweb.utils.DateUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;

/**
 * Created by mulan on 2016/10/11.
 */
public class SentModelMessageHandler
{
    /**
     * 门票支付成功提示模板
     */
    public static void sentSuccessPayModel(String orderNumber, String title,String verifyCode,String mobile,String email,Date payTime,String openId,Integer yuyue) throws IOException
    {
        sentSuccessPayModel(orderNumber, title,verifyCode,mobile,email,payTime,openId,null,null,yuyue);
    }

    /**
     * 支付成功提示模板
     */
    public static void sentSuccessPayModel(String orderNumber, String title,String verifyCode,String mobile,String email,Date payTime,String openId,String carBrand,String carNumber,Integer yuyue) throws IOException
    {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("touser",openId);
        map.put("template_id","uU4SyFQ8yuhBh4KBlZVqOOWXe7YSGFAFgYD8fEUdbv4");
        map.put("url", Constant.ContextPatameter.ORDER_DETAIL_PATH+orderNumber);

        Map<String,Object> map3 = new HashMap<String,Object>();
        Map<String,Object> map2 = new HashMap<String,Object>();
        map2.put("value", StrKit.notBlank(title)?title:"新西兰微助手订单");
        map2.put("color","#ff8c31");

        map3.put("name",map2);


        map2 = new HashMap<String,Object>();
        if(StrKit.notNull(carBrand) && StrKit.notNull(carNumber)){
            map2.put("value","验证码："+verifyCode+
                    "\n商家电话："+mobile+
                    "\n商家邮箱："+email+
                    "\n车牌号："+carNumber+
                    "\n车品牌："+carBrand+
                    "\n交易时间："+ DateUtil.dateToStr(payTime));

        }else{
            if(yuyue == 1){
                map2.put("value","验证码："+verifyCode+
                        "\n有效期:30天"+
                        "\n商家电话："+mobile+
                        "\n商家邮箱："+email+
                        "\n交易时间："+ DateUtil.dateToStr(payTime)+
                        "\n\n*使用前请发送您的姓名全拼,联系方式,体验时间和酒店地址至上述商家邮箱（或拨打商家电话）进行预约，预约时请说明订单来自 NZ Assistant。" +
                        "\n*也可直接微信留言联系微信客服进行预约"+
                        "\n*所有需要预约的订单至少提前24小时进行预约确认"
                );
            }else{
                map2.put("value","验证码："+verifyCode+
                        "\n有效期:30天"+
                        "\n商家电话："+ mobile+
                        "\n商家邮箱："+ email+
                        "\n交易时间："+ DateUtil.dateToStr(payTime)+
                        "\n\n*验证时请说明订单来自NZ Assistant"
                );
            }
        }
        map2.put("color","#ffa631");

        map3.put("remark",map2);

        map.put("data",map3);

        CloseableHttpClient client = HttpClients.createDefault();

        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", TokenHandler.getAccessToken());
        //String url = Constant.WeChatFinalValue.CREATE_MENU_URL.replace("ACCESS_TOKEN","dK1e3bUXwCE7L2hYuE8HYmstQ6WvNP4VONXnxBNDe7NqGekk-N-KWXHn5vgAgZJwsH1YL7PbIaJ-sS3VrblEtp-CaKEyJygS6hT-_1oD-p1t1u7df-2ZuSR4Q78NeZ5BCSLaAHAWMF");
        HttpPost post = new HttpPost(url);
        post.addHeader("Content/Type","application/json");
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), ContentType.create("application/json","UTF-8")) ;
        post.setEntity(stringEntity);
        CloseableHttpResponse resp = client.execute(post) ;

        int returnCode = resp.getStatusLine().getStatusCode() ;
        if(200<=returnCode && 300>=returnCode){
            System.out.println("发送支付完成模板消息\n"+EntityUtils.toString(resp.getEntity()));
        }
    }


    /**
     * 兑换码兑换成功模板
     * @param title 模板标题
     * @param verifyCode 兑换码
     * @param amount 兑换数量
     * @param openId 用户主键
     * @throws IOException 抛出异常
     */
    public static void sentVerifyOrderModel(String title,String verifyCode,int amount, String openId) throws IOException{
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("touser",openId);
        map.put("template_id","gA5p4jL17ZdN7z6tYCWw6PjwNpelZy_XMNit-kQavDU");
        map.put("url","http://www.baidu.com");

        Map<String,Object> map3 = new HashMap<String,Object>();
        Map<String,Object> map2 = new HashMap<String,Object>();
        map2.put("value", "商品名称");  // 模板抬头
        map2.put("color","#ff8c31");
        map3.put("productType",map2);

        map2 = new HashMap<String,Object>();
        map2.put("value", title);  // 模板抬头,商品标题
        map2.put("color","#ff8c31");
        map3.put("name",map2);

        map2 = new HashMap<String,Object>();
        map2.put("value", verifyCode);  // 模板内容，兑换码
        map2.put("color","#ff8c31");
        map3.put("certificateNumber",map2);

        map2 = new HashMap<String,Object>();
        map2.put("value", amount);  // 模板内容，兑换数量
        map2.put("color","#ff8c31");
        map3.put("number",map2);

        map2 = new HashMap<String,Object>();
        map2.put("value", "祝您旅途愉快");  // 模板结尾
        map2.put("color","#ff8c31");
        map3.put("remark",map2);

        map.put("data",map3);

        CloseableHttpClient client = HttpClients.createDefault();

        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", TokenHandler.getAccessToken());
        //String url = Constant.WeChatFinalValue.CREATE_MENU_URL.replace("ACCESS_TOKEN","dK1e3bUXwCE7L2hYuE8HYmstQ6WvNP4VONXnxBNDe7NqGekk-N-KWXHn5vgAgZJwsH1YL7PbIaJ-sS3VrblEtp-CaKEyJygS6hT-_1oD-p1t1u7df-2ZuSR4Q78NeZ5BCSLaAHAWMF");
        HttpPost post = new HttpPost(url) ;
        post.addHeader("Content/Type","application/json");
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), ContentType.create("application/json","UTF-8")) ;
        post.setEntity(stringEntity);
        CloseableHttpResponse resp = client.execute(post) ;

        int returnCode = resp.getStatusLine().getStatusCode() ;
        if(200<=returnCode && 300>=returnCode){
            System.out.println("发送验证兑换码成功模板消息\n"+EntityUtils.toString(resp.getEntity()));
        }
    }


    /**
     * 30天未消费，自动退款成功模板
     * @param openId 用户主键
     * @param amount   退款金额
     * @param title 模板标题，存在默认值
     * @param content   模板内容 存在默认值
     * @param orderNumber 订单号
     * @param contentTitle 内容标题，存在默认值
     * @throws Exception 抛出异常
     */
    public static void sentRefundModel1(String openId, Float amount,String title,String content,String orderNumber, String contentTitle) throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("touser",openId);
        map.put("template_id","e40TqC54C05kW9AmSA_K0oFG0Pvy1KyMxtLBPGw-ljE");
        map.put("url","");

        Map<String,Object> map3 = new HashMap<String,Object>();
        Map<String,Object> map2 = new HashMap<String,Object>();

        map2 = new HashMap<String,Object>();
        map2.put("value", title!=null?title:"您好，您的订单30天内未消费已自动退款");  // 模板抬头,商品标题
        map3.put("first",map2);

        map2 = new HashMap<String,Object>();
        map2.put("value", content !=null ? content:"验证码已过期");  // 退款原因
        map2.put("color","#ff8c31");
        map3.put("reason",map2);

        map2 = new HashMap<String,Object>();
        map2.put("value", amount+"元");  // 模板内容，兑换数量
        map2.put("color","#ff8c31");
        map3.put("refund",map2);

        map2 = new HashMap<String,Object>();
        map2.put("value", "商品名称:"+contentTitle
                +"\n订单号:"+orderNumber
                +"\n退款已原路返回，如需消费请重新购买");  // 模板结尾
        map3.put("remark",map2);

        map.put("data",map3);

        CloseableHttpClient client = HttpClients.createDefault();

        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", TokenHandler.getAccessToken());
        //String url = Constant.WeChatFinalValue.CREATE_MENU_URL.replace("ACCESS_TOKEN","dK1e3bUXwCE7L2hYuE8HYmstQ6WvNP4VONXnxBNDe7NqGekk-N-KWXHn5vgAgZJwsH1YL7PbIaJ-sS3VrblEtp-CaKEyJygS6hT-_1oD-p1t1u7df-2ZuSR4Q78NeZ5BCSLaAHAWMF");
        HttpPost post = new HttpPost(url) ;
        post.addHeader("Content/Type","application/json");
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), ContentType.create("application/json","UTF-8")) ;
        post.setEntity(stringEntity);
        CloseableHttpResponse resp = client.execute(post) ;

        int returnCode = resp.getStatusLine().getStatusCode() ;
        if(200<=returnCode && 300>=returnCode){
            System.out.println("发送验证兑换码成功模板消息\n"+EntityUtils.toString(resp.getEntity()));
        }
    }


    /**
     * 申请退款成功消息模板
     * @param openId 对象主键
     * @param amount 退款金额
     * @param orderNumber 订单号
     * @param title 模板标题 存在默认值
     * @throws Exception 抛出异常
     */
    public static void sentRefundModel(String openId, Float amount,String orderNumber, String title) throws Exception{
        sentRefundModel1(openId,amount,"您好,您申请的退款已成功！","用户申请退款",orderNumber,title);
    }

    /**
     * 自动退款的消息模板
     * @param openId 对象主键
     * @param amount    退款金额
     * @throws Exception    异常抛出
     */
    public static void sentAutoRefundModel(String openId, Float amount) throws Exception{
        sentRefundModel1(openId,amount,null,null,null,null);
    }

    public static void sentNewsModel(String openId ) throws IOException{
        List<String> list = new ArrayList<>();
        list.add(openId);
        list.add(openId);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("touser",list);
        map.put("msgtype","mpnews");
        map.put("send_ignore_reprint",1);

        Map<String,Object> map2 = new HashMap<String,Object>();
        map2.put("media_id","_IQ8Dtoxwwd7WyoSlB7PQCF8qojEWmogOHm5X9NiN3o");
        map.put("mpnews",map2);
        CloseableHttpClient client = HttpClients.createDefault();

        String url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", TokenHandler.getAccessToken());
        //String url = Constant.WeChatFinalValue.CREATE_MENU_URL.replace("ACCESS_TOKEN","dK1e3bUXwCE7L2hYuE8HYmstQ6WvNP4VONXnxBNDe7NqGekk-N-KWXHn5vgAgZJwsH1YL7PbIaJ-sS3VrblEtp-CaKEyJygS6hT-_1oD-p1t1u7df-2ZuSR4Q78NeZ5BCSLaAHAWMF");
        HttpPost post = new HttpPost(url) ;
        post.addHeader("Content/Type","application/json");
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), ContentType.create("application/json","UTF-8")) ;
        post.setEntity(stringEntity);
        CloseableHttpResponse resp = client.execute(post) ;

        int returnCode = resp.getStatusLine().getStatusCode() ;
        if(200<=returnCode && 300>=returnCode){
            System.out.println("发送验证兑换码成功模板消息\n"+EntityUtils.toString(resp.getEntity()));
        }
    }

    /**
     * 签证订单支付成功提示模板
     */
    public static void sentVisaOrderSuccessPayModel(String orderNumber, String title,String openId) throws IOException
    {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("touser",openId);
        map.put("template_id","uU4SyFQ8yuhBh4KBlZVqOOWXe7YSGFAFgYD8fEUdbv4");
        map.put("url", Constant.ContextPatameter.ORDER_DETAIL_PATH+orderNumber);

        Map<String,Object> map3 = new HashMap<String,Object>();
        Map<String,Object> map2 = new HashMap<String,Object>();
        map2.put("value", StrKit.notBlank(title)?title:"新西兰微助手签证订单");
        map2.put("color","#ff8c31");
        map3.put("name",map2);


        map2 = new HashMap<String,Object>();

        map2.put("color","#ffa631");

        map2.put("value","亲,您已成功下单,我们的工作人员将在一个工作日内与您联系。如有任何疑问可留言,谢谢!");
        map3.put("remark",map2);

        map.put("data",map3);

        CloseableHttpClient client = HttpClients.createDefault();

        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", TokenHandler.getAccessToken());
        //String url = Constant.WeChatFinalValue.CREATE_MENU_URL.replace("ACCESS_TOKEN","dK1e3bUXwCE7L2hYuE8HYmstQ6WvNP4VONXnxBNDe7NqGekk-N-KWXHn5vgAgZJwsH1YL7PbIaJ-sS3VrblEtp-CaKEyJygS6hT-_1oD-p1t1u7df-2ZuSR4Q78NeZ5BCSLaAHAWMF");
        HttpPost post = new HttpPost(url);
        post.addHeader("Content/Type","application/json");
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), ContentType.create("application/json","UTF-8")) ;
        post.setEntity(stringEntity);
        CloseableHttpResponse resp = client.execute(post) ;

        int returnCode = resp.getStatusLine().getStatusCode() ;
        if(200<=returnCode && 300>=returnCode){
            System.out.println("发送签证订单支付完成模板消息\n"+EntityUtils.toString(resp.getEntity()));
        }
    }

    /**
     * 签证订单支付成功提示模板
     */
    public static void SentVisaOrderSuccessPayModel(String orderNumber, String openId) throws IOException{
        sentVisaOrderSuccessPayModel(orderNumber,null,openId);
    }
}
